#!/usr/bin/env python
#!-*- coding:utf-8 -*-
import os
import datetime

from google.appengine.api import users    #using of google account 
from google.appengine.ext import webapp
from google.appengine.ext import db       #using of data storage
from google.appengine.ext.webapp import template

from db.OrderData import OrderData
from webapp.FileBlob import Storage
from db.tempFile import tempFile
from google.appengine.ext import blobstore

import wsgiref.handlers
import string
import csv
import codecs
import StringIO
from django.http import HttpResponse

class UserPrefs(db.Model): 
    name = db.StringProperty(required=True,multiline=False,verbose_name='ユーザー名')
    user = db.UserProperty(required=True,auto_current_user_add=True)
 

class OrderListPage(webapp.RequestHandler):
    def get(self):
            
        user = users.get_current_user() 
        if user: 
            q = db.GqlQuery("SELECT * FROM UserPrefs WHERE user = :1", user)
            result = q.fetch(limit=10)
 
            #userprefs = q.get()

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            current_user = users.get_current_user()
            view_data = db.GqlQuery("select * from OrderData")
            
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            current_user = users.get_current_user()
            view_data = OrderData()
        
        template_values = {
            'current_user':current_user,
            'url':url,
            'url_linktext':url_linktext,
            'view_data':view_data,
            }
        path = os.path.join(os.path.dirname(__file__),'../html/order_list.html')
        self.response.out.write(template.render((path),template_values))
        
    def post(self):
        #view
        current_order_number = self.request.get("order_number","create_new")
        filenameKey1 = ""
        
        files = []
        if current_order_number == "create_new" :
            #create new
            view_data = OrderData()
            #number,author,date
            view_data.order_number  = current_order_number
            view_data.order_author  = users.get_current_user()
            dt = datetime.datetime.today() + datetime.timedelta(hours=9)
#            view_data.order_date    =  dt.strftime('%Y-%m-%d %H:%M:%S')
            view_data.order_date    =  dt
            
        else:
            #modify
            view_datas = db.GqlQuery("select * from OrderData where order_number = :1",
                                    current_order_number)
#            view_datas = db.GqlQuery("select * from OrderData where order_number = :1",
#                                    "111")
#            view_data = db.GqlQuery("select * from OrderData")
#            order_count = view_datas.count();
            
#            for view_data in view_datas: 

            if view_datas.count() > 0:
                view_data = view_datas[0]
                
                # Blobstore に保存されているファイルを取得
                view_tempFile = tempFile()
                view_tempFiles = db.GqlQuery("select * from tempFile where order_number = :1",
                                        current_order_number)
                if view_tempFiles.count() > 0:
                    filename = ""
                    blob_key = ""
                    for fileData in view_tempFiles:
                        blob_key = (fileData.tempfile_key).decode('utf-8')
                        files1 = blobstore.BlobInfo.get(blob_key)
                        filename = fileData.tempfile_name
                        dic = {'foo':str(blob_key), 'bar':filename}
                        s = Storage(dic)
                        files.append(s)
        if view_data:
            
            view_data_front = {
               'order_number':view_data.order_number if view_data.order_number else "",

                'order_author':view_data.order_author if view_data.order_author else "",
                'order_dept':view_data.order_dept if view_data.order_dept else "",
                'order_author_title':view_data.order_author_title if view_data.order_author_title else "",
                'order_date':view_data.order_date if view_data.order_date else "",

                'estimate_contact_author':view_data.estimate_contact_author if view_data.estimate_contact_author else "",
                'estimate_contact_dept':view_data.estimate_contact_dept if view_data.estimate_contact_dept else "",
                'estimate_contact_author_title':view_data.estimate_contact_author_title if view_data.estimate_contact_author_title else "",
                'estimate_contact_date':view_data.estimate_contact_date if view_data.estimate_contact_date else "",

                'operation_author':view_data.operation_author if view_data.operation_author else "",
                'operation_dept':view_data.operation_dept if view_data.operation_dept else "",
                'operation_author_title':view_data.operation_author_title if view_data.operation_author_title else "",
                'operation_date':view_data.operation_date if view_data.operation_date else "",

                'confirm_author':view_data.confirm_author if view_data.confirm_author else "",
                'confirm_dept':view_data.confirm_dept if view_data.confirm_dept else "",
                'confirm_author_title':view_data.confirm_author_title if view_data.confirm_author_title else "",
                'confirm_date':view_data.confirm_date if view_data.confirm_date else "",

                'complete_contact_author':view_data.complete_contact_author if view_data.complete_contact_author else "",
#                'complete_contact_dept':view_data.complete_contact_dept if not None else "",
                'complete_contact_dept': view_data.complete_contact_dept if view_data.complete_contact_dept else "",
                'complete_contact_author_title':view_data.complete_contact_author_title if view_data.complete_contact_author_title else "",
                'complete_contact_date':view_data.complete_contact_date if view_data.complete_contact_date else "",

                'confirm_status':view_data.confirm_status if view_data.confirm_status else "",
                'confirm_message':view_data.confirm_message if view_data.confirm_message else "",

                'company_code':view_data.company_code if view_data.company_code else "",
                'company_name':view_data.company_name if view_data.company_name else "",
                'company_type':view_data.company_type if view_data.company_type else "",
                'company_service':view_data.company_service if view_data.company_service else "",

                'order_type':view_data.order_type if view_data.order_type else "",
                'order_content':view_data.order_content if view_data.order_content else "",
                'order_effect':view_data.order_effect if view_data.order_effect else "",

                'demand_release_date':view_data.demand_release_date if view_data.demand_release_date else "",
                'demand_service_date':view_data.demand_service_date if view_data.demand_service_date else "",

                'estimate_author':view_data.estimate_author if view_data.estimate_author else "",
                'estimate_develop':view_data.estimate_develop if view_data.estimate_develop else "",
                'estimate_cost':view_data.estimate_cost if view_data.estimate_cost else "",
                'estimate_release':view_data.estimate_release if view_data.estimate_release else "",
                'estimate_message':view_data.estimate_message if view_data.estimate_message else "",

                'complete_frontse':view_data.complete_frontse if view_data.complete_frontse else "",
                'complete_se':view_data.complete_se if view_data.complete_se else "",
                'complete_pg':view_data.complete_pg if view_data.complete_pg else "",
                'complete_status':view_data.complete_status if view_data.complete_status else "",

                'complete_service_date':view_data.complete_service_date if view_data.complete_service_date else "",
                'complete_message':view_data.complete_message if view_data.complete_message else "",
                
                'business_conditions':view_data.business_conditions if view_data.business_conditions else None,
                'stocktaking_methods':view_data.stocktaking_methods if view_data.stocktaking_methods else None,
                'classification':view_data.classification if view_data.classification else "0",
                'need_program':view_data.need_program if view_data.need_program else "0",
                
                'content':view_data.content if view_data.content else "",
                'effective':view_data.effective if view_data.effective else "",
                
                'attched_file_name':view_data.attched_file_name if view_data.attched_file_name else "",
                'attched_file':view_data.attched_file,
                'filenameKey1':view_data.filenameKey1,
                'files':files
                }
        
        path = os.path.join(os.path.dirname(__file__),'../html/order_detail.html')
        self.response.out.write(template.render((path),view_data_front))
